<?php

class Core_Table_Permission_Account extends Kd_Data_Table {

    public function __construct() {

    }

    public function insertRoleRelation($accountId, $areaId, array $roldIds, $transaction = NULL) {
        $insert = Kd_Data_Factory::getInsertDcl()
                        ->into('{t}permission_account_role')
                        ->value('account_id', ':accountId:i')
                        ->value('role_id', ':roleId:i')
                        ->toSql();
        $driver = $this->getDbDriver($transaction);
        foreach ($roldIds as $roleId) {
            if (!empty($roleId)) {
                $driver->setSql($insert, array('accountId' => $accountId, 'roleId' => $roleId))->execute();
            }
        }
        return $this;
    }

    public function deleteRoleRelation($accountId, $areaId, $transaction = NULL) {
        Kd_Data_Factory::getDeleteDcl()
                ->from('{t}permission_account_role')
                ->where()
	                ->eq('account_id', ':accountId:i')
                ->closest()
                ->addParameter(array('accountId' => $accountId))
                ->setDbDriver($this->getDbDriver($transaction))
                ->execute();
        return $this;
    }

    public function getRoleIds($accountId) {
        $query = Kd_Data_Factory::getQueryDcl()->from('{t}permission_account_role', 'a')
                ->eq('a.account_id', ':accountId:i')
              	->addParameter(array('accountId' => $accountId));
        $rs = $query->setDbDriver($this->getDbDriver())->fetch();
        $result = array();
        foreach ($rs as $row) {
            $result[] = $row['role_id'];
        }
        return $result;
    }

    public function getIdByUserName($userName) {
        return Kd_Data_Factory::getQueryDcl()
                ->from($this->getName())
                ->where()
                	->eq('user_name', ':userName:s')
                ->closest()
                ->select('id')->endSelf()
                ->addParameter('userName', $userName)
                ->fetch()
                ->getFirstValue();
    }

}